/* eslint-disable react/no-unstable-nested-components */
/* eslint-disable react-native/no-inline-styles */
import React, {useState} from 'react';
import AntdIcons from 'react-native-vector-icons/AntDesign';
import {ImageBackground, ScrollView, DeviceEventEmitter} from 'react-native';
import {connect} from 'react-redux';
import {
  Text,
  View,
  Colors,
  Avatar,
  ListItem,
  Button,
  Badge,
  Image,
  TouchableOpacity,
  Card,
} from 'react-native-ui-lib';
import {get, post, update} from '@/utils/request';
import {useRequest} from 'ahooks';
import ImageView from 'react-native-image-viewing';
import {logout} from '@/utils/service';
import Clipboard from '@react-native-clipboard/clipboard';
import {useNavigation, useIsFocused} from '@react-navigation/native';

const obj = {
  1: {
    text: '未提交',
    color: '#999999',
    pic: require('@/assets/day1.png'),
  },
  2: {
    text: '异常',
    color: '#ff0000',
    pic: require('@/assets/day2.png'),
  },
  3: {
    text: '正常',
    color: '#218000',
    pic: require('@/assets/day3.png'),
  },
};

const Mine = ({navigation, userInfo, appTheme, dispatch}) => {
  const Prefix = global.file;
  const {undo, doing, done, undoBg, doingBg, doneBg} = Colors ?? {};
  const {headUrl, name, userName, orgName, orgJoinKey, orgId} = userInfo ?? {};
  const [visible, setIsVisible] = useState(false);
  const header = Prefix + headUrl;
  const isfocused = useIsFocused();

  // 任务统计
  const useritemstatic = useRequest(
    async () => {
      if (!isfocused) {
        return;
      }
      let res = await get('/index/getUserItemStatistics', {
        days: 9999999,
        projectId: null,
      });
      return res?.data?.data;
    },
    {
      refreshDeps: [isfocused],
    },
  );

  // all report
  const {data, refresh} = useRequest(
    async () => {
      if (!isfocused) {
        return;
      }
      let res = await get('/itemWorkTime/pm');
      return res?.data?.dataList?.filter(it => it?.status === 2)?.[0] ?? {};
    },
    {
      refreshDeps: [isfocused],
    },
  );

  return (
    <ScrollView
      style={{
        backgroundColor: Colors.backgroundColor,
        flex: 1,
      }}>
      <ImageView
        presentationStyle="overFullScreen"
        images={visible || [{uri: ''}]}
        visible={visible?.length > 0}
        onRequestClose={() => setIsVisible([])}
      />
      <ImageBackground
        source={appTheme === 'light' ? require('@/assets/banner.png') : null}
        resizeMode="cover"
        style={{
          paddingHorizontal: 12,
          paddingTop: 48,
        }}>
        <View style={{position: 'relative'}}>
          <TouchableOpacity
            onPress={() => {
              navigation.navigate('Notice');
            }}>
            <View style={{position: 'absolute', right: 18, top: -20}}>
              <AntdIcons
                name="message1"
                size={21}
                color={Colors.colorTextBase}
              />
              <Badge
                label={useritemstatic?.data?.unReadNoticeNum}
                backgroundColor={Colors.primaryColor}
                labelStyle={{
                  color: Colors.backgroundColor,
                }}
                labelFormatterLimit={2}
                containerStyle={{position: 'absolute', right: -8, top: -4}}
                size={12}
              />
            </View>
          </TouchableOpacity>

          <TouchableOpacity
            onPress={() => {
              if (useritemstatic?.data?.workTimeStatus === 3) {
                DeviceEventEmitter.emit('toast', {
                  message: '今日日报已提交',
                  type: 'success',
                });
              } else {
                const isError = useritemstatic?.data?.workTimeStatus === 2;

                DeviceEventEmitter.emit('dialog', {
                  title: isError ? '今日日报异常' : '今日日报未提交',
                  type: 'bottom',
                  content: '是否跳转至日报界面?',
                  height: 120,
                  action: setState => (
                    <Button
                      label="填日报"
                      size="small"
                      style={{
                        borderRadius: 6,
                        width: 40,
                        backgroundColor: Colors.primaryColor,
                      }}
                      onPress={async () => {
                        navigation.navigate('Report');
                        setState(s => ({
                          ...s,
                          visible: false,
                        }));
                      }}
                    />
                  ),
                });
              }
            }}
            style={{position: 'absolute', left: 0, top: -38}}>
            <View center padding-8 style={{gap: 4}}>
              <Image
                source={obj?.[useritemstatic?.data?.workTimeStatus]?.pic}
                aspectRatio={1}
                style={{
                  borderRadius: 8,
                  width: 32,
                  height: 32,
                  borderColor: Colors.colorCardBg,
                  overflow: 'hidden',
                  backgroundColor: 'transparent',
                  opacity: 0.8,
                }}
              />
            </View>
          </TouchableOpacity>

          <View spread center>
            <View
              style={{
                borderWidth: 6,
                borderColor: Colors.colorBgSecondary,
                width: 112,
                height: 112,
              }}
              br100>
              <Avatar
                source={{
                  uri: header,
                }}
                size={100}
                label={headUrl ? null : name?.charAt(0)}
                onPress={() => {
                  setIsVisible([
                    {
                      uri: header,
                    },
                  ]);
                  dispatch({
                    type: 'CHANGE_THEME',
                    appTheme: appTheme === 'light' ? 'dark' : 'light',
                  });
                }}
              />
            </View>
          </View>

          <View style={{gap: 8}} marginT-36>
            <View row bottom>
              <View flex-1>
                <View row bottom>
                  <Text heading numberOfLines={1}>
                    {name}{' '}
                  </Text>
                  <Text subheading numberOfLines={1}>
                    / {userName}
                  </Text>
                </View>

                <View row center style={{gap: 6}}>
                  <View flex-1>
                    <Text body numberOfLines={1}>
                      {orgName}
                    </Text>
                  </View>
                </View>
              </View>

              <Button
                backgroundColor={Colors.primaryColor}
                label="编辑资料"
                size="small"
                onPress={() => {
                  navigation.navigate('FormPage', {
                    title: '编辑资料',
                    type: 'EditInfo',
                    currentUser: userInfo,
                  });
                }}
              />
            </View>
            <View marginT-12 row style={{gap: 10}} center>
              <View
                br40
                bottom
                backgroundColor={undoBg}
                padding-8
                flex-1
                style={{gap: 4}}>
                <Text subbody style={{color: undo}}>
                  未开始的任务
                </Text>
                <Text
                  style={{
                    color: undo,
                    fontSize: 18,
                    fontWeight: 'bold',
                  }}>
                  {useritemstatic?.data?.notStartCount}
                </Text>
              </View>
              <View
                br40
                bottom
                flex-1
                backgroundColor={doingBg}
                padding-8
                style={{gap: 4}}>
                <Text subbody style={{color: doing}}>
                  进行中的任务
                </Text>
                <Text
                  style={{
                    color: doing,
                    fontSize: 18,
                    fontWeight: 'bold',
                  }}>
                  {useritemstatic?.data?.onDoingCount}
                </Text>
              </View>
              <View
                br40
                bottom
                flex-1
                backgroundColor={doneBg}
                padding-8
                style={{gap: 4}}>
                <Text subbody style={{color: done}}>
                  已完成的任务
                </Text>
                <Text
                  style={{
                    color: done,
                    fontSize: 18,
                    fontWeight: 'bold',
                  }}>
                  {useritemstatic?.data?.finishCount}
                </Text>
              </View>
            </View>
            <TouchableOpacity
              onPress={() => {
                navigation.navigate('Audit');
              }}
              style={{
                flex: 1,
                backgroundColor: Colors.colorCardBg,
                borderRadius: 12,
                padding: 10,
                flexDirection: 'row',
                gap: 10,
                marginTop: 10,
                alignItems: 'center',
              }}>
              <Image
                source={require('@/assets/audit.png')}
                aspectRatio={1}
                style={{
                  borderRadius: 8,
                  width: 56,
                  height: 56,
                  borderColor: Colors.colorCardBg,
                  overflow: 'hidden',
                  backgroundColor: 'transparent',
                }}
              />
              <View gap={6} centerV left>
                <Text subbody>待审批日报</Text>
                <Text body>
                  <Text style={{fontSize: 20}} heading>
                    {data?.list?.length}{' '}
                  </Text>
                  条
                </Text>
              </View>
              <View flex-1 right paddingR-12>
                <AntdIcons name="arrowright" size={18} />
              </View>
            </TouchableOpacity>
          </View>
        </View>
      </ImageBackground>

      <View flex-1 row padding-12 left style={{gap: 12}}>
        <Card
          height={76}
          flex-1
          paddingH-12
          enableShadow={false}
          onPress={() => {
            navigation.navigate('FormPage', {
              title: '修改密码',
              type: 'ChangePwd',
            });
          }}
          center
          br40>
          <View height={24} bottom>
            <AntdIcons name="lock" size={26} color={Colors.colorTextBase} />
          </View>
          <Text body marginT-6 marginB-3 color={Colors.colorTextBase}>
            修改密码
          </Text>
        </Card>

        {!orgId ? (
          <Card
            flex-1
            height={76}
            paddingH-12
            enableShadow={false}
            onPress={() => {
              navigation.navigate('FormPage', {
                title: '加入组织',
                type: 'Join',
              });
            }}
            center
            br40>
            <View height={24} bottom>
              <AntdIcons
                name="addusergroup"
                size={23}
                color={Colors.colorTextBase}
              />
            </View>

            <Text body marginT-6 marginB-3 color={Colors.colorTextBase}>
              加入组织
            </Text>
          </Card>
        ) : (
          <Card
            height={76}
            paddingH-12
            flex-1
            enableShadow={false}
            onPress={() => {
              Clipboard.setString(orgJoinKey);
              DeviceEventEmitter.emit('toast', {
                message: '组织代码已复制！',
                type: 'success',
              });
            }}
            center
            br40>
            <View height={24} bottom>
              <AntdIcons
                name="sharealt"
                size={22}
                color={Colors.colorTextBase}
              />
            </View>
            <Text body marginT-6 marginB-3 color={Colors.colorTextBase}>
              复制组织代码
            </Text>
          </Card>
        )}
      </View>

      <View flex-1 row padding-12 paddingT-0 center style={{gap: 12}}>
        {!orgId && (
          <Card
            height={76}
            flex-1
            paddingH-12
            enableShadow={false}
            onPress={() => {
              DeviceEventEmitter.emit('dialog', {
                title: '是否退出?',
                type: 'bottom',
                content: '退出后将无法查看当前组织的项目,任务,成员,日报等信息',
                height: 120,
                action: setState => (
                  <Button
                    label="退出"
                    size="small"
                    style={{
                      borderRadius: 6,
                      width: 40,
                      backgroundColor: Colors.primaryColor,
                    }}
                    onPress={async () => {
                      let res = await update('/system/user', {orgId: 0});
                      if (res.code === 0) {
                        await logout(navigation);
                      }
                      setState(s => ({
                        ...s,
                        visible: false,
                      }));
                    }}
                  />
                ),
              });
            }}
            center
            br40>
            <View height={24} bottom>
              <AntdIcons
                name="deleteuser"
                size={20}
                color={Colors.colorTextBase}
              />
            </View>

            <Text body marginT-6 marginB-3 color={Colors.colorTextBase}>
              退出组织
            </Text>
          </Card>
        )}

        <Card
          height={76}
          flex-1
          paddingH-12
          enableShadow={false}
          onPress={async () => {
            await logout(navigation, true);
          }}
          center
          br40>
          <View height={24} bottom>
            <AntdIcons name="logout" size={20} color={Colors.colorTextBase} />
          </View>
          <Text body marginT-6 marginB-3 color={Colors.colorTextBase}>
            退出登录
          </Text>
        </Card>
      </View>
    </ScrollView>
  );
};

const mapStateToProps = state => {
  return {
    appTheme: state.appTheme,
    userInfo: state.userInfo,
  };
};

export default connect(mapStateToProps)(Mine);
